package serializer

import (
	"QImages/entity"
	"QImages/global"
	"log"
)

// Image 前端显示的图片信息
type Image struct {
	ID         uint      `json:"id"`
	CreatedAt  string    `json:"created_at"`
	Url        string    `json:"url"`
	Desc       string    `json:"desc"`
	Title      string    `json:"title"`
	Label      string    `json:"label"`
	Likes      int64     `json:"likes"`
	Comments   []Comment `json:"comments"`
	UserInfo   User      `json:"user_info"`
	Collectors []uint    `json:"collectors"`
}

// BuildImage 转化为前端显示的图片信息
func BuildImage(dbImage *entity.Image) Image {
	var res Image
	res.ID = dbImage.ID
	res.CreatedAt = dbImage.CreatedAt.Format("2006-01-02 15:04:05")
	res.Url = global.Config.PhotoPrefix + dbImage.Url
	res.Desc = dbImage.Desc
	res.Title = dbImage.Title
	res.Label = dbImage.Label
	res.Likes = dbImage.Likes
	if len(dbImage.Comments) == 0 {
		res.Comments = make([]Comment, 0)
	} else {
		for _, item := range dbImage.Comments {
			res.Comments = append(res.Comments, BuildComment(&item))
		}
	}
	dbUser, err := entity.FindUserById(dbImage.UserID)
	if err != nil {
		log.Println(err.Error())
	}
	res.UserInfo = BuildUser(&dbUser)
	collectors, err := entity.FindByImageID(dbImage.ID)
	if err != nil || collectors == nil {
		res.Collectors = make([]uint, 0)
	} else {
		res.Collectors = collectors
	}
	return res
}

// TimelineItem 时间线数据
type TimelineItem struct {
	Images []Image `json:"images"`
	Date   string  `json:"date"`
}

func BuildTimeline(timeline []entity.TimelineItem) (res []TimelineItem) {
	for _, dbItem := range timeline {
		var images []Image
		for _, dbImage := range dbItem.Images {
			images = append(images, BuildImage(&dbImage))
		}
		if len(images) == 0 {
			images = make([]Image, 0)
		}
		res = append(res, TimelineItem{
			Images: images,
			Date:   dbItem.Date,
		})
	}
	return
}
